package com.yvon.gprc.server.service;

import com.yvon.gprc.server.entity.DataType;
import com.yvon.grpc.api.Ip;
import com.yvon.grpc.api.Name;
import com.yvon.grpc.api.NameServersGrpc;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.server.service.GrpcService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @author : wangyufeng
 * @since : 2021-10-19
 */
@GrpcService
@Slf4j
public class NameServersService extends NameServersGrpc.NameServersImplBase {
    //记录名称内容的list，实际项目中应该放置在数据库
    private List<DataType> list = new ArrayList<DataType>();

    //构造方法中加入一些条目
    public NameServersService() {

        list.add(new DataType(Name.newBuilder().setName("Sunny").build(),Ip.newBuilder().setIp("125.216.242.51").build()));
        list.add(new DataType(Name.newBuilder().setName("Sunny").build(),Ip.newBuilder().setIp("126.216.242.51").build()));
        list.add(new DataType(Name.newBuilder().setName("David").build(),Ip.newBuilder().setIp("117.226.178.139").build()));
        list.add(new DataType(Name.newBuilder().setName("David").build(),Ip.newBuilder().setIp("117.227.178.139").build()));
        list.add(new DataType(Name.newBuilder().setName("Tom").build(),Ip.newBuilder().setIp("111.222.336.11").build()));
        list.add(new DataType(Name.newBuilder().setName("Tom").build(),Ip.newBuilder().setIp("111.333.336.11").build()));
        list.add(new DataType(Name.newBuilder().setName("Tom").build(),Ip.newBuilder().setIp("111.222.335.11").build()));

    }

    @Override
    public void getIpByName(Name request, StreamObserver<Ip> responseObserver) {
        for (DataType data : list) {
            if (request.equals(data.getName())) {
                System.out.println("get " + data.getIp() + " from " + request);
                responseObserver.onNext(data.getIp());
            }
        }
        responseObserver.onCompleted();
    }
}
